package test.designmode.chain;

import java.util.LinkedList;
import java.util.List;

/**
 * 责任链设计模式:
 * - 核心是任务队列(链表)+双接口
 */
public class ChainDemo {
    public static void main(String[] args) {
        DefaultExecutorChain chain = new DefaultExecutorChain();
        chain.addExecutor(c -> {
            System.out.println(123);
            c.execute();  // 这一句是责任链的关键, 控制要不要执行下一个任务 (参考Filter的放行)
        });

        chain.addExecutor(c -> {
            System.out.println(456);
        });

        chain.execute();

    }


    public static class DefaultExecutorChain implements ExecutorChain {

        private final List<MyExecutor> executorList = new LinkedList<>();
        private int position = 0;

        public void addExecutor(MyExecutor executor) {
            executorList.add(executor);
        }

        @Override
        public void execute() {
            int pos = position;
            MyExecutor executor = executorList.get(pos);
            System.out.println("执行任务号" + pos);
            position++;
            executor.exec(this);
        }
    }

    public interface MyExecutor {
        void exec(ExecutorChain chain);
    }

    public interface ExecutorChain {
        void execute();
    }
}
